/**
 * Created by Acery on 2016/12/13.
 */

$(function () {
    var bind_admin = function () {
        var self = $(this);
        var state;
        if (self.attr('id') == 'sayYes') {
            state = 1;
        }
        if (self.attr('id') == 'sayNo') {
            state = 2;
        }
        self.parent().find('#sayYes,#sayNo').attr('disabled', true);//3.1debug here
        setTimeout(function () {
            self.parent().find('#sayYes,#sayNo').attr('disabled', false);
        },3000);
        var demand_id = self.parent().find('.demand_id').html();
        var director_comment = $('#dctSgt').val();
        var school_comment = $('#sclSgt').val();
        $.ajax({
            type: 'post',
            url: '/admin/inspect/',
            data: {
                'demand_id': demand_id,
                'state': state,
                'director_comment': director_comment,
                'school_comment': school_comment
            },
            contentType: "application/x-www-form-urlencoded; charset=utf-8" //编码
        })
            .done(function (data) {
                data = JSON.parse(data);
                if (data.result == 'ok') {
                    if (state == 1) {
                        self.parent().find('#state').attr('hidden', false).html('已批准');
                        self.parent().find('#sayYes,#sayNo').remove();
                        self.parents('.aud-page').find('#sclSgt,#dctSgt').attr('disabled', true);
                    }//allow
                    if (state == 2) {
                        self.parent().find('#state').attr('hidden', false).html('已驳回');
                        self.parent().find('#sayYes,#sayNo').remove();
                        self.parents('.aud-page').find('#sclSgt,#dctSgt').attr('disabled', true);
                    }//resolve
                }
                else {
                    alert('error:' + data.error_str);
                }


            })
            .fail(function () {
                alert('error:net');
            })
    };

    $('#login').leanModal({top: 110, overlay: 0.6, closeButton: $('#close')});//modal login

    $('#date_query_href').leanModal({top: 110, overlay: 0.6, closeButton: $('.close')});//modal login

    $('#start').on('tap click', function (e) {
        e.preventDefault();
        var $self = $(this);
        var username = $('#adminId').val();
        var password = $('#adminPwd').val();
        // console.log(password,username);
        if (!username || !password) {
            $('#mention').html('用户名密码不能为空!');
            return false;
        }
        $self.attr('disabled', true);
        setTimeout(function () {
            $self.attr('disabled', false);
            $('#mention').html('');
        }, 2000);
        // var dfd = $.Deferred();
        $.ajax({
            type: 'post',
            url: '/admin/login/',
            data: {
                'username': username,
                'password': password
            },
            contentType: "application/x-www-form-urlencoded; charset=utf-8" //编码
        })
            .done(function (data) {
                data = JSON.parse(data);
                if (data.result == 'ok') {
                    // username='hello';
                    $('#mention').html('登录成功！');
                    window.sessionStorage.setItem('userName', username);
                    setTimeout(function () {
                        $('#lean_overlay,#login_modal').fadeOut(300);
                        $('#login').html('已登录');
                        $('#normal_query,#date_query_href').css('display', 'block');
                    }, 800)
                } else {
                    $('#mention').html('账号或密码错误');
                    setTimeout(function () {
                        $('#mention').html('');
                    }, 2000);
                    return false
                }
            })
            .fail(function (data) {
                data = JSON.parse(data);
                alert('error:' + data.error_str);
            });     //login request
    });//login event

    $('#normal_query').on('click tap', function () {
        $.ajax({
            type: 'get',
            url: '/admin/list/',
            data: {
                'cookie': document.cookie
            },
            contentType: "application/x-www-form-urlencoded; charset=utf-8" //编码
        })
            .done(function (data) {
                data = JSON.parse(data);
                if (data.result == 'ok') {
                    dataList = data.list;
                    if (dataList.length == 0) {
                        alert('没有更多请假条了');
                        return false
                    }
                    $('.aud-page').children().remove();
                    for (var i = 0; i < dataList.length; i++) {
                        $('#list').append('<li> <div class="page"> <div class="page-left"></div> <div class="page-row page-us"> <span >' + dataList[i].stu_name + '</span> <span class="sm-text">' + dataList[i].stu_id + '</span> </div> <div class="page-row"> <span>' + dataList[i].start_time + '</span> <span>至</span> <span>' + dataList[i].stop_time + '</span> </div> <div class="page-row"> <span>理由：' + dataList[i].reason + '</span> <span class="pos-right">地点：' + dataList[i].location + '</span> </div> <div class="page-bottom1"> <span class="sm-text">学院意见</span> <input class="audtext" type="text" required/> </div> <div class="page-bottom2"> <span class="sm-text">导员意见</span> <input class="audtext" type="text" required/> </div> <div class="page-right"> <div> <span class="sm-text">学生电话</span> <span class="sm-text sm-tel">' + dataList[i].stu_phone + '</span> </div> <div> <span class="sm-text">家长电话</span> <span class="sm-text sm-tel">' + dataList[i].parent_phone + '</span> </div> <div class="btn-group"><button class="adm-btn1" id="sayNo">驳回</button><button class="adm-btn2" id="sayYes">同意</button><p class="demand_id" hidden>' + dataList[i].demand_id + '</p><p id="state" hidden>' + dataList[i].state + '</p> </div> </div> </div> </li>')
                        if (dataList[i].state == 1) {
                            $('.aud-page li:eq(' + i + ')').find('#sayYes,#sayNo').remove();
                            $('.aud-page li:eq(' + i + ')').find('#state').attr('hidden', false).html('已批准');
                        }//resolved
                        if (dataList[i].state == 2) {
                            $('.aud-page li:eq(' + i + ')').find('#sayYes,#sayNo').remove();
                            $('.aud-page li:eq(' + i + ')').find('#state').attr('hidden', false).html('已驳回');
                        }//reject
                    }
                    $('#sayYes,#sayNo').unbind('click');
                    $('#sayYes,#sayNo').bind('click tap', bind_admin);
                } else {
                    console.log(data.error_str);
                    alert('error!wrong operation');
                }

            })
            .fail(function (xhr) {
                alert('net error ' + xhr.status);//ajax error 2nd
            })
    });//normal require event

    $('#start_query').on('click tap', function () {
        var self = $(this);
        var dataList = null;
        var start_time = $('#start-time').val();
        var stop_time = $('#stop-time').val();
        var num = $('#query_num').val();
        // console.log(start_time, stop_time, num);
        if (!start_time || !stop_time || !num) {
            $('#date_query_mention').html('请填写完整信息以查询');
            return false;
        }
        self.attr('disabled', true);
        $.ajax({
            type: 'get',
            url: '/admin/history/',
            data: {
                'start_time': start_time,
                'stop_time': stop_time,
                'limit': num
            },
            contentType: "application/x-www-form-urlencoded; charset=utf-8" //编码
        })
            .done(function (data) {
                data = JSON.parse(data);
                if (data.result == 'ok') {
                    $('#lean_overlay,#date_query_modal').fadeOut(300);
                    self.attr('disabled', false);
                    $('.aud-page').children().remove();//remove the old
                    dataList = data.list;
                    if (dataList.length == 0) {
                        alert('没有更多请假条了');
                        return false
                    }
                    for (var i = 0; i < dataList.length; i++) {
                        $('#list').append('<li> <div class="page"> <div class="page-left"></div> <div class="page-row page-us"> <span >' + dataList[i].stu_name + '</span> <span class="sm-text">' + dataList[i].stu_id + '</span> </div> <div class="page-row"> <span>' + dataList[i].start_time + '</span> <span>至</span> <span>' + dataList[i].stop_time + '</span> </div> <div class="page-row"> <span>理由：' + dataList[i].reason + '</span> <span class="pos-right">地点：' + dataList[i].location + '</span> </div> <div class="page-bottom1"> <span class="sm-text">学院意见</span> <input class="audtext" type="text" required/> </div> <div class="page-bottom2"> <span class="sm-text">导员意见</span> <input class="audtext" type="text" required/> </div> <div class="page-right"> <div> <span class="sm-text">学生电话</span> <span class="sm-text sm-tel">' + dataList[i].stu_phone + '</span> </div> <div> <span class="sm-text">家长电话</span> <span class="sm-text sm-tel">' + dataList[i].parent_phone + '</span> </div> <div class="btn-group"> <button class="adm-btn1" id="sayNo">驳回</button> <button class="adm-btn2" id="sayYes">同意</button><p id="demand_id" hidden>' + dataList[i].demand_id + '</p><p id="state" hidden>' + dataList[i].state + '</p> </div> </div> </div> </li>')
                        if (dataList[i].state == 1) {
                            console.log('判断请假条状态1')
                            $('.aud-page li:eq(' + i + ')').find('#sayYes,#sayNo').remove();
                            $('.aud-page li:eq(' + i + ')').find('#state').attr('hidden', false).html('已批准');
                        }//resolved
                        console.log('state:' + dataList[i].state);
                        if (dataList[i].state == 2) {
                            console.log('判断请假条状态2')
                            $('.aud-page li:eq(' + i + ')').find('#sayYes,#sayNo').remove();
                            $('.aud-page li:eq(' + i + ')').find('#state').attr('hidden', false).html('已驳回');
                        }//reject
                    }
                    // console.log('重载脚本');
                    $('#sayYes,#sayNo').unbind('click');
                    $('#sayYes,#sayNo').bind('click tap', bind_admin);

                } else {
                    alert('无法查询，请检查所输入字段');
                    self.attr('disabled', false);
                }
            })
            .fail(function () {
                alert('error:net');
                self.attr('disabled', false);
            })

    });//date require event

    if (window.sessionStorage.getItem('userName') != null && document.cookie != '') {
        $('#login').html('已登录:' + window.sessionStorage.getItem('userName'));

        $('#normal_query,#date_query_href').css('display', 'block');
    } else {
        $('#login').trigger('click');
    }


    let indexDate = new Date();
    let list = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
    $('#start-time').val(indexDate.getFullYear() + '-' + list[indexDate.getMonth()] + '-01 00:00')
    $('#stop-time').val(indexDate.getFullYear() + '-' + list[indexDate.getMonth()] + '-' + (indexDate.getDate() + 1) + ' 23:59')
});
